package com.example.spring_start.controller;

import com.example.pojo.User;
import com.example.req.LoginUserReq;
import com.example.req.LoginUserSaveReq;
import com.example.req.UserReq;
import com.example.resp.CommonResp;
import com.example.resp.LoginUserResp;
import com.example.resp.PageResp;
import com.example.spring_start.service.UserService;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;


@RestController
@RequestMapping("/login-user")
@CrossOrigin(origins = "http://localhost:8015")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("register")
    public CommonResp register(@Valid @RequestBody LoginUserSaveReq req){
        req.setUserpassword(DigestUtils.md5DigestAsHex(req.getUserpassword().getBytes()));
        CommonResp resp = new CommonResp<>();
        userService.register(req);
        return resp;
    }

    @PostMapping("/saveUser")
    public CommonResp saveUser(@Valid @RequestBody LoginUserSaveReq loginUserSaveReq){
        loginUserSaveReq.setUserpassword(DigestUtils.md5DigestAsHex(loginUserSaveReq.getUserpassword().getBytes()));
        CommonResp resp = new CommonResp<>();
        userService.saveUser(loginUserSaveReq);
        return resp;
    }

    @PostMapping("login")
    public CommonResp login(@Valid @RequestBody LoginUserReq req){
        req.setUserpassword(DigestUtils.md5DigestAsHex(req.getUserpassword().getBytes()));
        CommonResp<LoginUserResp> resp = new CommonResp<>();
        LoginUserResp loginUserResp = userService.login(req);
        resp.setContent(loginUserResp);
        return resp;
    }

    @GetMapping("/getUserList")
    public CommonResp getUserList(UserReq userReq){
        CommonResp<PageResp<User>> resp = new CommonResp<>();
        PageResp<User> list = userService.getUserList(userReq);
        resp.setContent(list);
        return resp;
    }
}
